package iec104;

public class ASDU {

	public static final int M_SP_NA_1 = 1;
	public static final int M_SP_TA_1 = 2;
	public static final int M_DP_NA_1 = 3;
	public static final int M_DP_TA_1 = 4;
	public static final int M_ST_NA_1 = 5;
	public static final int M_ST_TA_1 = 6;
	public static final int M_BO_NA_1 = 7;
	public static final int M_ME_NA_1 = 9;
	public static final int M_ME_TA_1 = 10;
	public static final int M_ME_NB_1 = 11;
	public static final int M_ME_NC_1 = 13;
	public static final int M_IT_NA_1 = 15;
	public static final int M_IT_TA_1 = 16;
	public static final int M_PS_NA_1 = 20;
	public static final int M_ME_ND_1 = 21;
	public static final int M_SP_TB_1 = 30;
	public static final int M_DP_TB_1 = 31;
	public static final int M_ME_TD_1 = 34;
	public static final int M_ME_TE_1 = 35;
	public static final int M_ME_TF_1 = 36;
	public static final int M_IT_TB_1 = 37;
	public static final int C_SC_NA_1 = 45;
	public static final int C_DC_NA_1 = 46;
	public static final int C_RC_NA_1 = 47;
	public static final int C_SE_NA_1 = 48;
	public static final int C_SE_NB_1 = 49;
	public static final int C_SE_NC_1 = 50;
	public static final int M_EI_NA_1 = 70;
	public static final int C_IC_NA_1 = 100;
	public static final int C_CI_NA_1 = 101;
	public static final int C_CS_NA_1 = 103;
	public static final int P_VA_TA_1 = 137;

	private short rtu = 0; // 2

	private int len = 0;

	ASDU() {
	}
	ASDU(int rtu) {
		setRtu(rtu);
	}
	private void setRtu(int rtu) {
		this.rtu = (short) rtu;
	}

	protected short[] PackageAsdu(int typeid, int vsq, int reason, short[] body, int bodylen) {
		if (bodylen > 255) {
			return null;
		}
		len = 0;
		short[] asdu = new short[1024];
		asdu[len++] = (short) typeid;
		asdu[len++] = (short) vsq;
		asdu[len++] = (short) reason;
		asdu[len++] = (short) (reason >> 8);
		asdu[len++] = (short) (rtu & 0xff);
		asdu[len++] = (short) ((rtu >> 8) & 0xff);
		System.arraycopy(body, 0, asdu, len, bodylen);
		len += bodylen;
		return asdu;
	}

	public int getAsdulen() {
		return len;
	}

	protected short[] TranslateAsdu(String asdu) {
		if (asdu.isEmpty()) {
			return null;
		}
		asdu = asdu.replace(" ", "");
		int num = asdu.trim().length() / 2;
		short[] asduarray = new short[num];
		for (int index = 0, offset = 0; index < asdu.trim().length(); index += 2, offset++) {
			short high = (short) (Character.digit(asdu.charAt(index), 16) & 0xff);
			short low = (short) (Character.digit(asdu.charAt(index + 1), 16) & 0xff);
			asduarray[offset] = (short) (high << 4 | low);
		}
		return asduarray;
	}
}
